package com.lwq.fast.log.fastlogclient.logback.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lwq.fast.log.fastlogclient.logback.appender.util.MessageUtil;
import com.lwq.fast.log.fastlogcore.client.redis.RedisClient;
import com.lwq.fast.log.fastlogcore.client.rocketmq.RocketMqClient;
import com.lwq.fast.log.fastlogcore.entity.Message;
import com.lwq.fast.log.fastlogcore.util.ThreadPoolUtil;
import com.lwq.fast.log.fastlogcore.work.MessageCollection;
import org.apache.rocketmq.client.producer.DefaultMQProducer;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义 appender 使用rocketmq 来收集日志
 *
 * @author 刘文强
 */
public class RocketMqAppender extends AppenderBase<ILoggingEvent> {

    /**
     * 应用名称
     */
    private String appName;
    /**
     * 环境信息  如： dev， test, prod 等
     */
    private String env;


    /**
     * rocketmq namesrvAddr
     */
    private String namesrvAddr;

    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        // 讲消息放入队列暂存
        Message message = MessageUtil.formatMessage(appName, env, iLoggingEvent);
        if (ObjectUtil.isNotNull(message)) {
            MessageCollection.addMessage2Queue(JSON.toJSONString(message));
        }
    }

    @Override
    public void start() {
        super.start();
        //初始化
        RocketMqClient instance = RocketMqClient.getInstance(namesrvAddr);
        if (ObjectUtil.isNotNull(instance)){
            // 从队列中获取消息，发送到 MQ中
            ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.getThreadPoolExecutor();
            threadPoolExecutor.execute(() -> {
                MessageCollection.messageCollect(instance);
            });
        }


    }
    @Override
    public void stop() {
       /* RocketMqClient instance = RocketMqClient.getInstance(namesrvAddr);
        if (ObjectUtil.isNotNull(instance)){
            DefaultMQProducer producer = instance.getProducer();
            if (ObjectUtil.isNotNull(producer)){
                producer.shutdown();
            }
        }*/
        super.stop();
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getEnv() {
        return env;
    }

    public void setEnv(String env) {
        this.env = env;
    }

    public String getNamesrvAddr() {
        return namesrvAddr;
    }

    public void setNamesrvAddr(String namesrvAddr) {
        this.namesrvAddr = namesrvAddr;
    }
}
